<template>
  <div class="app-container">
    <el-card shadow="always" style="margin-top: 20px;">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="160px">
    <el-row :gutter="20">
      <el-col :span="22">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="模板名" prop="templateName">
      <el-input
        v-model="queryParams.templateName"
        placeholder="请输入模板名"
        clearable
        @keyup.enter.native="handleQuery"
      />
    </el-form-item>
    <el-form-item label="项目类型" prop="projectType">
      <el-select v-model="queryParams.projectType" placeholder="请选择项目类型" clearable>
        <el-option
          label="纵向"
          value="纵向"
        ></el-option>
        <el-option
          label="横向"
          value="横向"
        ></el-option>
      </el-select>
    </el-form-item>

        </el-col>
      </el-row>
      </el-col>

      <!-- 第二列 -->
      <el-col :span="2">
        <el-row>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        </el-form-item>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-row>
      </el-col>
      </el-row>
    </el-form>
    </el-card>
    <el-card shadow="always" style="margin-top: 20px;">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:template:add']"
        >新增</el-button>
      </el-col>



      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板ID" align="center" prop="templateId" />
      <el-table-column label="模板名" align="center" prop="templateName" />
      <el-table-column label="项目类型" align="center" prop="projectType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sci_paper_pub_status" :value="scope.row.projectType"/>
        </template>
      </el-table-column>
      <el-table-column label="启用状态" align="center" prop="enableStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enableStatus === 1 ? 'success' : 'info'">
            {{ scope.row.enableStatus === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="toggleEnableStatus(scope.row)"
            v-hasPermi="['system:template:edit']"
          >
            {{ scope.row.enableStatus === 1 ? '禁用' : '启用' }}
          </el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:template:edit']"
          >修改</el-button> -->

           <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:template:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    </el-card>

    <!-- 添加或修改预算模板维护对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">

          <el-col :span="12">
            <el-form-item label="模板名" prop="templateName">
              <el-input v-model="form.templateName" placeholder="请输入模板名"/>
            </el-form-item>
            </el-col>
            <el-col :span="12">
            <el-form-item label="项目类型" prop="projectType">
              <el-select v-model="form.projectType" placeholder="请选择项目类型" style="width: 100%;" clearable>
                <el-option
                  label="纵向"
                  value="纵向"
                ></el-option>
                <el-option
                  label="横向"
                  value="横向"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
       <el-divider content-position="center">预算科目配置信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddSciBudgetSubject()">添加根节点</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteSciBudgetSubject">删除</el-button>
          </el-col>
        </el-row>
        <el-table
          :data="treeData"
          :row-class-name="rowSciBudgetSubjectIndex"
          @selection-change="handleSciBudgetSubjectSelectionChange"
          ref="sciBudgetSubject"
          row-key="index"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          default-expand-all
        >
          <el-table-column type="selection" width="50" align="center" />

          <el-table-column label="科目名称" prop="subjectName" width="400">
            <template slot-scope="scope">
              <div :style="{ paddingLeft: (scope.row.subjectLevel - 1) * 20 + 'px' }">
                <span v-if="scope.row.subjectLevel > 1"></span>
                <el-input v-model="scope.row.subjectName" placeholder="请输入科目名称" />
              </div>
            </template>
          </el-table-column>
          <el-table-column label="科目层级" prop="subjectLevel">
            <template slot-scope="scope">
              <span>{{ scope.row.subjectLevel }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排序序号" prop="sortOrder" width="220">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.sortOrder" :min="1" controls-position="right" />
            </template>
          </el-table-column>
          <el-table-column label="是否可编辑" prop="editable" width="200">
            <template slot-scope="scope">
              <el-select v-model="scope.row.editable" placeholder="请选择">
                <el-option label="否" :value="0" />
                <el-option label="是" :value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="是否汇总行" prop="isSummary" width="200">
            <template slot-scope="scope">
              <el-select v-model="scope.row.isSummary" placeholder="请选择">
                <el-option label="否" :value="0" />
                <el-option label="是" :value="1" />
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding" width="200">
            <template slot-scope="scope">
              <el-button
                type="text"
                icon="el-icon-circle-plus"
                size="mini"
                @click.stop="handleAddChild(scope.row)"
                :disabled="scope.row.subjectLevel >= 5"
              >
                添加下级
              </el-button>
              <el-button
                type="text"
                icon="el-icon-delete"
                size="mini"
                @click.stop="handleDeleteRow(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 查看预算模板维护抽屉 -->
    <el-drawer
      :title="viewTitle"
      :visible.sync="viewOpen"
      direction="rtl"
      size="40%"
      :before-close="handleClose"
      :show-close="true"
      custom-class="view-drawer"
    >
      <el-form :model="viewForm" label-width="120px" style="padding: 20px;">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板名">
              <span class="view-content">{{ viewForm.templateName }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目类型">
              <span class="view-content">{{ viewForm.projectType }}</span>
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">预算科目配置信息</el-divider>

        <el-table
          :data="viewTreeData"
          row-key="index"
          :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
          default-expand-all

          height="calc(100vh - 300px)"
        >
          <el-table-column label="科目名称" prop="subjectName" width="400">
            <template slot-scope="scope">
              <div :style="{ paddingLeft: (scope.row.subjectLevel - 1) * 20 + 'px' }">
                <span>{{ scope.row.subjectName }}</span>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="科目层级" prop="subjectLevel" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.subjectLevel }}</span>
            </template>
          </el-table-column>

          <el-table-column label="排序序号" prop="sortOrder" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.sortOrder }}</span>
            </template>
          </el-table-column>

          <el-table-column label="是否可编辑" prop="editable" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.editable === 0 ? '否' : '是' }}</span>
            </template>
          </el-table-column>

          <el-table-column label="是否汇总行" prop="isSummary" width="120">
            <template slot-scope="scope">
              <span>{{ scope.row.isSummary === 0 ? '否' : '是' }}</span>
            </template>
          </el-table-column>
        </el-table>

        <div style="text-align: right; margin-top: 20px;">
          <el-button @click="viewOpen = false">关 闭</el-button>
        </div>
      </el-form>
    </el-drawer>

  </div>
</template>

<script>
import { listTemplate, getTemplate, delTemplate, addTemplate, updateTemplate,updateTemplateStatus } from "@/api/sci/budgetTemplate";

export default {
  name: "Template",
  dicts: ['sci_paper_pub_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedSciBudgetSubject: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 预算模板维护表格数据
      templateList: [],
      // 预算科目配置表格数据（原始平级数据）
      sciBudgetSubjectList: [],
      // 树形结构数据
      treeData: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      // 查看弹出层标题
      viewTitle: "",
      // 是否显示查看弹出层
      viewOpen: false,
      // 查看表单
      viewForm: {},
      // 查看树形数据
      viewTreeData: [],


      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        templateName: null,
        projectType: null,
        enableStatus: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [
          { required: true, message: "模板名不能为空", trigger: "blur" }
        ],
        projectType: [
          { required: true, message: "项目类型不能为空", trigger: "change" }
        ],
        enableStatus: [
          { required: true, message: "启用状态不能为空", trigger: "change" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询预算模板维护列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        templateId: null,
        templateName: null,
        projectType: null,
        enableStatus: null,
      };
      this.sciBudgetSubjectList = [];
      this.treeData = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.templateId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加预算模板";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const templatesToUodate = row.templateId ? [row] : this.templateList.filter(item => this.ids.includes(item.templateId));

      // 检查是否有启用状态的模板
      const enabledTemplates = templatesToUodate.filter(template => template.enableStatus === 1);
      if (enabledTemplates.length > 0) {
        this.$modal.msgWarning("启用状态下的模板不能修改，请先禁用再修改");
        return;
      }

      this.reset();
      const templateId = row.templateId || this.ids
      getTemplate(templateId).then(response => {
        this.form = response.data;
        this.sciBudgetSubjectList = response.data.sciBudgetSubjectList;
        this.treeData = this.buildTree(this.sciBudgetSubjectList);
        this.open = true;
        this.title = "修改预算模板";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.sciBudgetSubjectList = this.flattenTree(this.treeData);
          if (this.form.templateId != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {

      const templatesToDelete = row.templateId ? [row] : this.templateList.filter(item => this.ids.includes(item.templateId));

      // 检查是否有启用状态的模板
      const enabledTemplates = templatesToDelete.filter(template => template.enableStatus === 1);
      if (enabledTemplates.length > 0) {
        this.$modal.msgWarning("启用状态下的模板不能删除，请先禁用再删除");
        return;
      }

      const templateIds = row.templateId || this.ids;
      this.$modal.confirm('是否确认删除预算模板维护编号为"' + templateIds + '"的数据项？').then(function() {
        return delTemplate(templateIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 预算科目配置序号 */
    rowSciBudgetSubjectIndex({ row, rowIndex }) {
      row.index = row.index || new Date().getTime() + rowIndex; // 确保每个节点都有唯一index
    },

     /** 切换启用状态 */
    toggleEnableStatus(row) {
      // 如果是要启用项目，则检查是否已有同类型启用的项目
      if (row.enableStatus !== 1) {
        // 查找是否有同类型且已启用的项目
        const sameTypeEnabled = this.templateList.find(template =>
          template.projectType === row.projectType &&
          template.enableStatus === 1 &&
          template.templateId !== row.templateId
        );

        if (sameTypeEnabled) {
          this.$modal.msgWarning(`已存在启用的同类型项目：${sameTypeEnabled.templateName}，不能同时启用多个同类型项目`);
          return;
        }
      }

      // 创建一个新对象，只包含需要更新的字段
      const updateData = {
        templateId: row.templateId,
        enableStatus: row.enableStatus === 1 ? 0 : 1
      };

      // 调用更新接口
      updateTemplateStatus(updateData).then(response => {
        // 更新成功后，更新当前行的状态
        row.enableStatus = updateData.enableStatus;
        this.$modal.msgSuccess(`${updateData.enableStatus === 1 ? '启用' : '禁用'}成功`);
        // 重新加载列表以确保状态同步
        this.getList();
      }).catch(error => {
        this.$modal.msgError(`${row.enableStatus === 1 ? '禁用' : '启用'}失败`);
        console.error(error);
      });
    },
    /** 预算科目配置添加按钮操作 - 添加根节点 */
     handleAddSciBudgetSubject() {
      let obj = {};
      obj.parentId = null; // 保留parentId为空
      obj.tempParentId = 0; // 根节点tempParentId为0
      obj.tempId = null; // tempId将在flattenTree中分配
      obj.subjectName = "";
      obj.subjectLevel = 1;
      obj.sortOrder = 1;
      obj.editable = 0;
      obj.isSummary = 0;
      obj.createdBy = "";
      obj.createdTime = "";
      obj.updatedBy = "";
      obj.updatedTime = "";
      obj.isDeleted = 0;
      obj.index = new Date().getTime(); // 使用时间戳作为唯一标识
      obj.children = [];

      this.treeData.push(obj);
      this.$forceUpdate(); // 强制更新视图
    },
    /** 预算科目配置添加子节点操作 - 在指定行添加子节点 */
    handleAddChild(parentRow) {
      // 检查层级是否超过5级
      if (parentRow.subjectLevel >= 5) {
        this.$modal.msgWarning("科目层级最多为5级");
        return;
      }

      let obj = {};
      obj.parentId = null; // 保留parentId为空
      obj.tempParentId = null; // tempParentId将在flattenTree中分配
      obj.tempId = null; // tempId将在flattenTree中分配
      obj.subjectName = "";
      obj.subjectLevel = parentRow.subjectLevel + 1;
      obj.sortOrder = 1;
      obj.editable = 0;
      obj.isSummary = 0;
      obj.createdBy = "";
      obj.createdTime = "";
      obj.updatedBy = "";
      obj.updatedTime = "";
      obj.isDeleted = 0;
      obj.index = new Date().getTime() + Math.random(); // 使用时间戳+随机数作为唯一标识
      obj.children = [];

      // 如果父节点还没有children数组，则创建一个
      if (!parentRow.children) {
        parentRow.children = [];
      }

      parentRow.children.push(obj);

      // 展开父节点
      this.$refs.sciBudgetSubject.toggleRowExpansion(parentRow, true);
      this.$forceUpdate(); // 强制更新视图
    },
    /** 删除单行数据 */
    handleDeleteRow(row) {
      this.$modal.confirm('是否确认删除科目名称为"' + row.subjectName + '"的数据项？').then(() => {
        this.treeData = this.removeNodes(this.treeData, [row.index]);
        this.$modal.msgSuccess("删除成功");
        this.$forceUpdate(); // 强制更新视图
      }).catch(() => {});
    },
    /** 预算科目配置删除按钮操作 */
    handleDeleteSciBudgetSubject() {
      if (this.checkedSciBudgetSubject.length == 0) {
        this.$modal.msgError("请先选择要删除的预算科目配置数据");
      } else {
        const checkedIndexes = this.checkedSciBudgetSubject.map(item => item.index);
        this.treeData = this.removeNodes(this.treeData, checkedIndexes);
        this.$forceUpdate(); // 强制更新视图
      }
    },
    /** 复选框选中数据 */
    handleSciBudgetSubjectSelectionChange(selection) {
      this.checkedSciBudgetSubject = selection;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },

    /** 构建树形结构 */
    buildTree(data) {
      // 为每个节点添加唯一标识index
      const dataWithIndex = data.map((item, index) => {
        // 确保每个节点都有唯一index
        const nodeIndex = item.subjectId || item.index || new Date().getTime() + index;
        return {
          ...item,
          tempId: item.tempId !== undefined ? item.tempId : 0, // 默认tempId为0
          tempParentId: item.tempParentId !== undefined ? item.tempParentId : (item.parentId || 0),
          index: nodeIndex,
          children: []
        };
      });

      const map = {};
      const roots = [];

      // 构建映射
      dataWithIndex.forEach(item => {
        map[item.index] = item;
      });

      // 构建父子关系
      dataWithIndex.forEach(item => {
        if (item.tempParentId === 0 || !map[item.tempParentId]) {
          roots.push(item);
        } else {
          if (!map[item.tempParentId].children) {
            map[item.tempParentId].children = [];
          }
          map[item.tempParentId].children.push(item);
        }
      });

      return roots;
    },


    /** 扁平化树形结构 */
    flattenTree(nodes, result = []) {
      // 先收集所有节点
      const allNodes = [];
      const collectNodes = (nodes, tempParentId = 0) => {
        nodes.forEach(node => {
          allNodes.push({
            node,
            tempParentId
          });
          if (node.children && node.children.length > 0) {
            collectNodes(node.children, null); // tempParentId将在后续分配
          }
        });
      };
      collectNodes(nodes);

      // 为每个节点分配tempId
      allNodes.forEach((item, index) => {
        item.node.tempId = index + 1; // 从1开始编号
      });

      // 重新设置tempParentId关系
      const assignRelations = (nodes, tempParentId = 0) => {
        nodes.forEach(node => {
          const { children, index: nodeIndex, ...rest } = node;

          // 查找当前节点的tempId
          const currentNode = allNodes.find(item => item.node === node);
          const currentTempId = currentNode ? currentNode.node.tempId : 0;

          // 添加到结果中
          const flatNode = {
            ...rest,
            tempId: currentTempId,
            tempParentId: tempParentId,
            parentId: null // 保留parentId为空
          };
          result.push(flatNode);

          if (children && children.length > 0) {
            assignRelations(children, currentTempId);
          }
        });
      };

      assignRelations(nodes);

      return result;
    },


      /** 删除节点 */
    removeNodes(nodes, indexesToRemove) {
      return nodes.filter(node => {
        if (indexesToRemove.includes(node.index)) {
          return false;
        }
        if (node.children && node.children.length > 0) {
          node.children = this.removeNodes(node.children, indexesToRemove);
        }
        return true;
      });
    },
    /** 查看按钮操作 */
      handleView(row) {
        const templateId = row.templateId;
        getTemplate(templateId).then(response => {
          this.viewForm = response.data;
          this.viewTreeData = this.buildTree(response.data.sciBudgetSubjectList);
          this.viewTitle = `查看预算模板 - ${response.data.templateName}`;
          this.viewOpen = true;
        });
      },

      /** 关闭抽屉 */
      handleClose(done) {
        this.viewOpen = false;
        done();
      }

  }
};
</script>

<style scoped>
.view-content {
  display: block;
  padding: 8px 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #606266;
  font-size: 14px;
}

/* 抽屉样式优化 */
.view-drawer {
  overflow-y: auto;
}

.view-drawer .el-drawer__header {
  margin-bottom: 0;
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
}

.view-drawer .el-drawer__body {
  padding: 20px;
  overflow-y: auto;
}

/* 响应式调整 */
@media screen and (max-width: 768px) {
  .el-drawer__container {
    width: 100% !important;
  }

  .el-drawer__body {
    padding: 15px;
  }
}
</style>
